package cn.jdemo.juc.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @see ForkJoinPool#invoke(ForkJoinTask)  有Join(使主线程挂起等候task结果), tasks会被同步到主进程
 * @see ForkJoinPool#submit(ForkJoinTask)  异步执行，且带Task返回值，可通过task.get 实现同步到主线程
 * @see ForkJoinPool#execute(ForkJoinTask) 异步执行tasks，无返回值
 */
public class Demo01 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Demo01 demo01 = new Demo01();
        demo01.test01();
    }

    public void test01() throws ExecutionException, InterruptedException {
        ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime().availableProcessors());

        ForkJoinTaskHandler handler = new Demo01().new ForkJoinTaskHandler(new Hero());

        String resInvoke = pool.invoke(handler);
        String res = handler.invoke();
    }

    public class ForkJoinTaskHandler extends RecursiveTask<String> {
        private Hero hero;
        ForkJoinTaskHandler(Hero hero){
            this.hero = hero;
        }

        @Override
        protected String compute() {
            // todo:递归终止条件
            ForkJoinTaskHandler handler1 = new ForkJoinTaskHandler(new Hero());
            ForkJoinTaskHandler handler2 = new ForkJoinTaskHandler(new Hero());
            ForkJoinTaskHandler handler3 = new ForkJoinTaskHandler(new Hero());
            invokeAll(handler1,handler2,handler3);
            String join1 = handler1.join();
            String join2 = handler1.join();
            String join3 = handler1.join();
            return join1+join2+join3;
        }
    }
}
